package main

import (
	"net/http"

	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

var log = logrus.WithFields(logrus.Fields{"filename": "main.go"})

func EchoMessage(w http.ResponseWriter, r *http.Request) {
	upgrader.CheckOrigin = func(r *http.Request) bool {
		return true
	}
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Error("连接失败", err)
		return
	}
	go func(conn *websocket.Conn) {
		for {
			log.Info("新连接加入：", conn.RemoteAddr())
			messageType, msg, err := conn.ReadMessage()
			if err != nil {
				log.Error("连接失败", err)
				return
			}
			conn.WriteMessage(messageType, msg)
		}
	}(conn)

}

func main() {
	log.Info("启动")
	http.HandleFunc("/v1/ws", EchoMessage)
	http.HandleFunc("/look", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("dddd"))
	})
	err := http.ListenAndServe(":8888", nil)
	log.Error(err)

}
